package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileHelper;
import com.ruoyi.system.mapper.SysFileInfoMapper;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.service.ISysFileInfoService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件表(SysFileInfo)表服务实现类
 *
 * @author jiuling
 * @since 2022-11-15 10:34:20
 */
@Service
public class SysFileInfoServiceImpl extends ServiceImpl<SysFileInfoMapper, SysFileInfo> implements ISysFileInfoService {

    @Resource
    private SysFileInfoMapper fileInfoMapper;

    @Override
    public Map<String, String> getFilePathMap(@NotEmpty Collection<?> groupIdColl) {
        List<SysFileInfo> fileInfoList = fileInfoMapper.selectList(new QueryWrapper<SysFileInfo>().lambda().in(CollUtil.isNotEmpty(groupIdColl), SysFileInfo::getGroupId, groupIdColl));
        Map<String, String> map = fileInfoList.stream().filter(e -> e.getGroupId() != null).collect(Collectors.toMap(SysFileInfo::getGroupId, SysFileInfo::getFilePath, (k1, k2) -> k2));
        map.put(null, FileHelper.getDefaultFilePath());
        return map;
    }

    @Override
    public Map<String, List<SysFileInfo>> getFilePathMapList(@NotEmpty Collection<?> groupIdColl) {
        List<SysFileInfo> fileInfoList = fileInfoMapper.selectList(new QueryWrapper<SysFileInfo>().lambda().in(CollUtil.isNotEmpty(groupIdColl), SysFileInfo::getGroupId, groupIdColl));
        return fileInfoList.stream().filter(e -> e.getGroupId() != null).collect(Collectors.groupingBy(SysFileInfo::getGroupId));
    }


    @Override
    public String getFilePathByGroupId(String groupId) {
        if (StringUtils.isNull(groupId)){
            return FileHelper.getDefaultFilePath();
        }
        SysFileInfo fileInfo = fileInfoMapper.selectOne(new LambdaQueryWrapper<SysFileInfo>().eq(SysFileInfo::getGroupId, groupId));
        if (StringUtils.isNull(fileInfo)){
            return FileHelper.getDefaultFilePath();
        }
        return fileInfo.getFilePath();
    }
}

